package util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class MyFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化filter");

    }

    @Override
    //请求和相应时都会执行doFilter()方法
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("过滤器开始");

        //处理乱码
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        request.setCharacterEncoding("utf-8");

        //防止用户在未登录的情况下访问资源
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求地址
        String requestURI = request.getRequestURI();
        System.out.println("requestURI为:"+requestURI);
        Object userName = request.getSession().getAttribute("userName");

        //endsWith()方法,判断字符串是否已xxx结束；字符串以xxx开始可用startsWith()方法
        if (requestURI.endsWith("success.jsp") && userName==null){
            response.sendRedirect("index.jsp");
        }


        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("过滤器结束");

    }

    @Override
    public void destroy() {
        System.out.println("销毁filter");

    }
}
